<!DOCTYPE html>

<html lang="en">

<head>


    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>



</head>

<body onload="init()">

    <button id="btn">点击授权</button>
    <script src="js/jweixin-1.6.0.js"></script>
    <script src="js/jquery-3.2.1.min.js"></script>
    <script src="js/monkey-loading-movieclip-v3.2.min.js"></script>
    <script src="js/Monkey-Gyroscope.js"></script>
    <script type="text/javascript">
        document.getElementById("btn").addEventListener("click", function() {

            if (typeof DeviceMotionEvent.requestPermission === 'function') {
                DeviceMotionEvent.requestPermission().then(permissionState => {
                    if (permissionState === 'granted') {
                        window.addEventListener('devicemotion', deviceMotionHandler, false);
                    }
                }).catch((err) => {
                    alert("用户未允许权限");
                });
            } else {
                alert("not found")
            }

        })

        var SHAKE_THRESHOLD = 1500;

        var last_update = 0;

        var x = y = z = last_x = last_y = last_z = 0;

        function init() {

            if (window.DeviceMotionEvent) {

                if (typeof DeviceMotionEvent.requestPermission === 'function') {

                    DeviceMotionEvent.requestPermission()

                    .then(permissionState => {

                        if (permissionState === 'granted') {

                            window.addEventListener('devicemotion', deviceMotionHandler, false);

                        }

                    })

                    .catch((err) => {

                        alert("用户未允许权限");

                    });

                } else {

                    window.addEventListener('devicemotion', deviceMotionHandler, false);

                }

            } else {

                alert('not support mobile event');

            }

        }

        function deviceMotionHandler(eventData) {

            var acceleration = eventData.accelerationIncludingGravity;

            var curTime = new Date().getTime();

            if ((curTime - last_update) > 100) {

                var diffTime = curTime - last_update;

                last_update = curTime;

                x = acceleration.x;

                y = acceleration.y;

                z = acceleration.z;

                var speed = Math.abs(x + y + z - last_x - last_y - last_z) / diffTime * 10000;

                if (speed > SHAKE_THRESHOLD) {

                    alert("摇动了");

                }

                last_x = x;

                last_y = y;

                last_z = z;

            }

        }
    </script>

</body>

</html>